package com.yonyou.wdt.job;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yonyou.wdt.dao.JobLogDao;
import com.yonyou.wdt.entity.QueryDto;
import com.yonyou.wdt.job.config.BaseConfig;
import com.yonyou.wdt.model.JobLogModel;
import com.yonyou.wdt.service.YonsuiteService;
import com.yonyou.wdt.utils.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

@Component
public class YsTaxToRedisJob extends BaseConfig {
    private static Logger logger = LoggerFactory.getLogger(YsProductToRedisJob.class);
    @Resource
    public JobLogDao jobLogDao;
    @Resource
    private YonsuiteService yonsuiteService;


    @XxlJob("YsTaxToRedisJob")
    public ReturnT<String> ysTaxToRedisJob() {
        // 处理相关业务
        QueryDto dto = new QueryDto();
        dto.setTenantId(getYsTenantId());
        dto.setAppKey(getYsAppKey());
        dto.setAppSecret(getYsAppSecret());
        // 获取YS系统租户动态域名信息
        ReturnT<String> isReturn2 = getYsDynamicDomainName(dto);
        // 域名获取失败
        if (isReturn2 != null) return isReturn2;
        try {
            HashMap<String, Object> queryMap = new HashMap<>();
            queryMap.put("pageIndex", 1);
            queryMap.put("pageSize", 500);
            // 税率档案列表查询
            JSONObject outTaxRes = yonsuiteService.ysTaxListQuery(queryMap, dto);
            if ("200".equals(outTaxRes.getStr("code"))) {
                JSONArray recordList = null != outTaxRes.getJSONObject("data") && null != outTaxRes.getJSONObject("data").getJSONArray("recordList") ? outTaxRes.getJSONObject("data").getJSONArray("recordList") : new JSONArray();
                for (Object taxObj : recordList) {
                    JSONObject taxJson = (JSONObject) taxObj;
                    RedisUtils.set(dto.getTenantId() + ":TAX:" + taxJson.getStr("id"), taxJson.getBigDecimal("ntaxrate"));
                }
                InsertLogger(null, "1", "YS税率档案同步Redis缓存任务执行完成，共：{" + recordList.size() + "}条");
                logger.info("YS税率档案同步Redis缓存任务执行完成，共：{}条", recordList.size());
            } else {
                XxlJobHelper.handleFail(outTaxRes.getStr("message"));
                InsertLogger(null, "0", outTaxRes.getStr("message"));
                return ReturnT.FAIL;
            }
        } catch (Exception e) {
            XxlJobHelper.handleFail(e.getMessage());
            InsertLogger(null, "0", e.getMessage());
            return ReturnT.FAIL;
        }
        return ReturnT.SUCCESS;
    }

    public ReturnT<String> getYsDynamicDomainName(QueryDto ysQueryDto) {
        try {
            String tenantId = ysQueryDto.getTenantId();  // 租户ID
            if (RedisUtils.get(tenantId + ":DynamicDomainName") == null) {
                // 根据租户ID查询动态域名
                JSONObject dynamicDomainName = yonsuiteService.getDynamicDomainName(null, tenantId);
                if (null != dynamicDomainName && !dynamicDomainName.isEmpty()) {
                    // 将动态域名存入Redis
                    RedisUtils.set(tenantId + ":DynamicDomainName", dynamicDomainName, 86400 * 30);
                } else {
                    logger.error("查询租户【{}】动态域名失败，请重试", tenantId);
                    // insertXxlJobLog(null, "0", "租户：【" + tenantId + "】获取动态域名失败，请稍后重试", jobClassType);
                    InsertLogger(null, "0", "获取动态域名失败");
                    return new ReturnT<>(ReturnT.FAIL_CODE, "查询租户【" + tenantId + "】动态域名失败，请重试");
                }
            }
            // 获取Redis中指定租户动态域名
            JSONObject dynamicDomainNameRedis = (JSONObject) RedisUtils.get(tenantId + ":DynamicDomainName");
            ysQueryDto.setGatewayUrl(dynamicDomainNameRedis.getStr("gatewayUrl"));
            ysQueryDto.setTokenUrl(dynamicDomainNameRedis.getStr("tokenUrl"));
            return null;
        } catch (Exception e) {
            return new ReturnT<>(ReturnT.FAIL_CODE, "获取动态域名失败：" + e.getMessage());
        }
    }

    /**
     * @return
     * @Author Huangwb
     * @Description 插入数据库日志信息
     * @Date 10:30 2023/9/14
     * @Param
     **/
    private void InsertLogger(String code, String oneL, String mags) {  // 单据编号、是否成功、详细信息
        try {
            JobLogModel jobLogDTO = new JobLogModel();
            jobLogDTO.setJobClass("HYZM001");
            jobLogDTO.setJobCode(code);
            jobLogDTO.setJobTime(new Date());
            jobLogDTO.setJobResult(oneL);
            jobLogDTO.setJobResultMessage(mags);
            jobLogDTO.setJobLogUser("dxroot");
            jobLogDao.insertJobLog(jobLogDTO);
        } catch (Exception e) {
            logger.error("插入日志错误：" + e.getMessage());
        }
    }
}
